package com.cloudcreativity.blyg.ui;

import android.app.Activity;
import android.content.Intent;
import android.databinding.ObservableField;
import android.os.Handler;

import com.cloudcreativity.blyg.base.BaseDialogImpl;
import com.cloudcreativity.blyg.base.BaseModel;
import com.cloudcreativity.blyg.databinding.ActivityMainBinding;
import com.cloudcreativity.blyg.entity.CategoryWrapper;
import com.cloudcreativity.blyg.entity.GoodsWrapper;
import com.cloudcreativity.blyg.receiver.MyBusinessReceiver;
import com.cloudcreativity.blyg.sqlite.CategoryOne;
import com.cloudcreativity.blyg.sqlite.Goods;
import com.cloudcreativity.blyg.sqlite.utils.CategoryDaoUtils;
import com.cloudcreativity.blyg.sqlite.utils.GoodsDaoUtils;
import com.cloudcreativity.blyg.ui.account.DayAccountAC;
import com.cloudcreativity.blyg.ui.account.MonthAccountAC;
import com.cloudcreativity.blyg.ui.account.SellStatisticsAC;
import com.cloudcreativity.blyg.ui.cashier.CashierAC;
import com.cloudcreativity.blyg.ui.goods.GoodsListActivity;
import com.cloudcreativity.blyg.ui.provider.ProviderListAC;
import com.cloudcreativity.blyg.ui.setting.SettingAC;
import com.cloudcreativity.blyg.utils.AlertDialogUtils;
import com.cloudcreativity.blyg.utils.DefaultObserver;
import com.cloudcreativity.blyg.utils.HttpUtils;
import com.cloudcreativity.blyg.utils.InitializeDialog;
import com.cloudcreativity.blyg.utils.LogUtils;
import com.cloudcreativity.blyg.utils.SPUtils;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class MainModel extends BaseModel<Activity, ActivityMainBinding> {

    private CategoryDaoUtils categoryDaoUtils;
    private GoodsDaoUtils goodsDaoUtils;

    public ObservableField<String> shopName = new ObservableField<>();

    MainModel(final Activity context, ActivityMainBinding binding, BaseDialogImpl baseDialog) {
        super(context, binding, baseDialog);

        shopName.set(SPUtils.get().getUser().getShopName());

//        //app 检查更新
//        UpdateManager.checkVersion(context,getBaseDialog());


        //第一次加载数据
        goodsDaoUtils = new GoodsDaoUtils(context);

        if(goodsDaoUtils.count()<=0){
            categoryDaoUtils = new CategoryDaoUtils(context);

            new Thread(new InitializeTask(context)).start();
        }else{
            LogUtils.e("xuxiwu","基础商品信息已存在");
        }

    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    public void onSettingClick(){
        context.startActivity(new Intent(context, SettingAC.class));
    }

    public void onCashierClick(){
        context.startActivity(new Intent(context, CashierAC.class));
    }

    public void onWaterClick(){
        context.startActivity(new Intent(context, SellStatisticsAC.class));
    }

    public void onProviderClick(){
        context.startActivity(new Intent(context, ProviderListAC.class));
    }

    public void onDayClick(){
        context.startActivity(new Intent(context, DayAccountAC.class));
    }

    public void onMonthClick(){
        context.startActivity(new Intent(context, MonthAccountAC.class));
    }

    public void onGoodsClick(){
        context.startActivity(new Intent(context, GoodsListActivity.class));
    }

    public void onLogout(){
        AlertDialogUtils dialogUtils = new AlertDialogUtils(context,"提示",
                "确定退出登录吗?");
        dialogUtils.setOnResultListener(new AlertDialogUtils.OnResultListener() {
            @Override
            public void onOk() {
                Intent intent = new Intent();
                intent.setAction(MyBusinessReceiver.ACTION_LOGOUT);
                context.sendBroadcast(intent);
            }

            @Override
            public void onCancel() {

            }
        });
        dialogUtils.show();
    }

    /**
     * 第一次加载数据
     */
    class InitializeTask implements Runnable{

        private int page = 1;
        private static final int size = 100;

        private InitializeDialog dialog;

        InitializeTask(Activity context) {
            dialog = new InitializeDialog(context);
            context.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dialog.setMessage("设备初始化，请勿操作。请稍后...");
                    dialog.show();
                }
            });
        }

        @Override
        public void run() {
            //先加载分类
            HttpUtils.getInstance().getAllCategories()
                    .subscribeOn(Schedulers.io())
                    .observeOn(Schedulers.io())
                    .subscribe(new DefaultObserver<CategoryWrapper>(getBaseDialog(),
                            false) {
                        @Override
                        public void onSuccess(CategoryWrapper t) {

                            //将信息保存
                            categoryDaoUtils.insertAllCategoryOne(t.getInfo());
                            for(CategoryOne categoryOne:t.getInfo()){
                                categoryDaoUtils.insertAllCategoryTwo(categoryOne.getSeconds());
                            }

                            //加载商品信息
                            loadGoods();
                        }

                        @Override
                        public void onFail(ExceptionReason msg) {
                            error();
                        }
                    });
        }

        private void loadGoods(){
            HttpUtils.getInstance().getAllGoods(page,size)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new DefaultObserver<GoodsWrapper>(getBaseDialog(),false) {
                        @Override
                        public void onSuccess(GoodsWrapper t) {
                            if(t.getInfo().getRecords().isEmpty()){
                                //数据加载完成
                                complete();
                            }else{
                                //将数据存入数据库
                                for(Goods g:t.getInfo().getRecords()){
                                    //将本地的localId优先设置为中央仓库id
                                    g.setLid(g.getId());
                                    //初始化库存200
                                    g.setStock(200);
                                }
                                goodsDaoUtils.insertAll(t.getInfo().getRecords());
                                page ++;
                                loadGoods();
                            }
                        }

                        @Override
                        public void onFail(ExceptionReason msg) {
                            //出错
                            error();
                        }
                    });
        }

        private void complete(){
            context.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dialog.setMessage("初始化成功，欢迎使用");
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            dialog.dismiss();
                        }
                    },1000);
                }
            });
        }
        private void error(){
            context.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dialog.setMessage("初始化失败，请重试");
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            dialog.dismiss();
                            context.finish();
                        }
                    },1000);
                }
            });
        }
    }

}
